﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Visitor;
using Taste;

namespace ASTClass
{
    class TasteAST : AST
    {
        public TasteAST() : base() { name = "Taste"; }
        public TasteAST(AST parent) : base(parent) { name = "Taste"; }

        public override AST Clone()
        {
            TasteAST ast = new TasteAST();
            ast.operators = operators;
            foreach (AST c in children)
                ast.children.Add(c.Clone());
            return ast;
        }

        #region Visitor pattern

        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }

        #endregion Visitor pattern

        public override void CodeGen(SymbolTable st, CodeFileGen cfg)
        {
            cfg.AddFuncName("__Entry");
            cfg.AddCommand("jal", "Main");
            cfg.AddCommand("nop", string.Empty);
            cfg.AddCommand("li", "$v0, 10");
            cfg.AddCommand("syscall", string.Empty);
            int i = 0;
            foreach (AST child in children)
            {
                if (child.Name == "VarDecl")
                {
                    foreach (AST grandchild in child.Children)
                    {
                        if (grandchild.Name == "Ident")
                        {

                            Var x = new Var(grandchild as IdentAST);
                            st.insertGlobalVar(x);
                            cfg.AddDataConst((grandchild as IdentAST).Value, CodeFileGen.DataType.WORD, x.index * 4 + "");
                            i++;
                        }
                    }
                }
            }
            for (i = 1; i < children.Count(); i++ )
                children[i].CodeGen(st, cfg);
        }
    }
}
